#include "ledseg.h"
#include "soc_comm.h"


code uint8_t m_seg7NumArray[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};

void LedSegInit(LedSegDev_t *dev)
{
    int i;

    dev->index = 0;
    for(i = 0; i < LEDSEG_PSEL_MAX; i++)
    {
        dev->values[i] = 0;
    }
}

void LedSegSetDigitalPin(LedSegDev_t *dev, uint8_t port, uint8_t startPin, int count)
{
    int i;

    for(i = 0; i < count; i++)
    {
        dev->pDigital[i] = S_PORT_PIN_DEF(port, startPin++);
    }
}

void LedSegSetSelectedPin(LedSegDev_t *dev, uint8_t port, uint8_t startPin, int count)
{
    int i;

    for(i = 0; i < count; i++)
    {
        dev->pSel[i] = S_PORT_PIN_DEF(port, startPin++);
    }
}

void LedSegSetValueByPos(LedSegDev_t *dev, int pos, uint8_t value)
{
    if(pos < 0 || pos >= LEDSEG_PSEL_MAX)
    {
        return;
    }
}

void LedSegSetValue(LedSegDev_t *dev, uint32_t value)
{
    int i;

    for(i = LEDSEG_PSEL_MAX - 1; i >= 0; i--)
    {
        dev->values[i] = value % 10;

        value /= 10;
    }
}

void LedSegSetDp(LedSegDev_t *dev, int pos, bool value)
{
    if(pos < 0 || pos >= LEDSEG_PSEL_MAX)
    {
        return;
    }

    if(value)
    {
        dev->values[pos] |= 0x80;
    }
    else 
    {
        dev->values[pos] &= ~0x80;
    }
}

void LedSegUpdate(LedSegDev_t *dev)
{
    int i;
    uint8_t num;
    uint8_t segNum;
    
    num = dev->values[dev->index];
    segNum = m_seg7NumArray[num];

    for(i = 0; i < LEDSEG_PSEL_MAX; i++) 
    {
        SOC_GpioWriteExt(dev->pSel[i], 1);
    }

    for (i = 0; i < 8; i++) 
    {
        if(IS_BIT_SET(segNum, i))
        {
            SOC_GpioWriteExt(dev->pDigital[i], 1);
        }   
        else 
        {
            SOC_GpioWriteExt(dev->pDigital[i], 0);
        }
    }   

    SOC_GpioWriteExt(dev->pSel[dev->index], 0);

    dev->index = (dev->index + 1) % LEDSEG_PSEL_MAX;
}
